<template>
	<view class="content">
		<view style="background-color: #f3f3f3;">
			<u-row>
				<u-col span="12">
					<view style="padding:5px;background-color: #F3F3F3;height:40px;">
						<u-search placeholder="搜索产品" search-icon-color="#bc927a" border-color="#bc927a"
							v-model="keyword" :show-action="false" @search='searchProduct'>
						</u-search>
					</view>
				</u-col>
			</u-row>
			<view class="container">
				<!-- 左右滑动按钮条 -->
<!-- 				<scroll-view class="scroll-view" scroll-x :show-scrollbar="false" :scroll-into-view="currentId">
					<view class='button-item' style='background-color: #f3f3f3;padding:0px;margin:0px;'>
						{{ leftButton }}
					</view>
					<view v-for="(item, index) in itemList" :key="index" :id="'btn' + index" class="button-item"
						:class="{ active: categoryId === item.id }" @click="setCategory(item.id)">
						{{ item.__toString }}
					</view>
				</scroll-view> -->
			</view>
		</view>
		<view style="width:100vw;">
			<scroll-view class="left" scroll-y>
				<view v-for="(item,index) in categories" style="text-align:center;height:calc(10vh - 10px)"
					:key='index'>
					<view v-if="choosedCategory == item.id" class="active">
						<view style="padding:13px">
							<view
								style="font-size:12px;height: 34px;display: flex;align-items: center;justify-content: center;font-weight: bold;">
								{{item.name}}
							</view>
						</view>
					</view>
					<view v-else @click="changeCategory(item.id)">
						<view style="padding:13px 10px">
							<view
								style="font-size:12px;height: 34px;display: flex;align-items: center;justify-content: center;">
								{{item.name}}
							</view>
						</view>
					</view>
				</view>
			</scroll-view>
			<scroll-view class="right" scroll-y scroll-x lower-threshold="20">
				<view v-if="tagCategories && tagCategories.length > 0" style='padding-bottom:65px'>
					<view v-for="item in tagCategories">
						<view class="t-container">
							<!-- 顶部标题 -->
							<view class="t-title">{{item.name}}</view>
							<view class="image-grid">
								<view v-for='tag in item.tags' class='image-div'>
									<img :src="tag.image" style='width:100%;height:100%;border-radius: 10px;'
										mode='widthFix'
										@click='toUrl(`/pages/product/search?tag=${tag.id}&categoryId=${categoryId}`)'>
									<view style='text-align: center;font-size:14px;color:#606266'>{{tag.name}}</view>
								</view>
							</view>
						</view>
					</view>
				</view>
				<view v-else style="height: 80vh;">
					<view v-if='products && products.length > 0'>
						<view class="product" v-for="item in products">
							<view class='activity-item' @click='toUrl(`/pages/product/detail?id=${item.id}`)'>
								<image class="product-img" :src="item.cover" mode="aspectFit"></image>
								<view class="product-info">
									<view class="product-name">{{ item.name }}</view>
									<view>
										<text class='category-name'>
											{{item.category.__toString}}
										</text>
									</view>
									<view class="product-price">
										¥{{ item.specifications ? item.specifications[0].price : item.price }}
									</view>
								</view>
							</view>
						</view>
					</view>
					<view v-else>
						<u-empty text="暂无分类" mode="list"></u-empty>
					</view>
				</view>
			</scroll-view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				showCategory: false,
				showStores: false,
				categories: [],
				keyword: '',
				choosedCategory: 0,
				tagCategories: [],
				itemList: [],
				leftButton: '《',
				categoryId: 0,
				products: []
			}
		},
		onLoad() {
			uni.removeStorageSync('cart')
			uni.removeTabBarBadge({
				index: 2
			})
			// 针对无token的进行登录,因为扫门店码，所以不需要定位
			const token = uni.getStorageSync('api_token')
			if (token == '') {
				this.wxlogin()
			} else {
				this.getCategories()
			}
		},
		onShow() {

		},
		methods: {
			toUrl(url) {
				uni.navigateTo({
					url: url
				})
			},
			//获取分类
			getCategories() {
				uni.showLoading()
				this.request.get(`api/categories`, {
					'@filter': `entity.getEnabled() == true && !entity.getParent() && entity.getType().getSlug() == 'ProductCategory'`,
					'@display': "['id','name','children']",
					'@order': 'entity.sequence|ASC',
				}).then((res) => {
					console.log('category', res.data)
					let promise = []
					this.categories = res.data
					// let itemList = []
					// for (let i of res.data[0].children) {
					// 	if (i.type.id == 1) {
					// 		itemList.push(i)
					// 	}
					// }
					// itemList.sort((a,b) => {
					// 			return a.sequence - b.sequence
					// 		})
					// this.itemList = itemList
					this.choosedCategory = res.data[0].id
					this.getTags()
				})

			},
			// 获取产品标签
			getTags() {
				uni.showLoading()
				this.tagCategories = []
				this.products = []
				this.request.get(`api/categories`, {
					'@filter': `entity.getParent().getId() == ${this.choosedCategory} && entity.getEnabled() == true && entity.getType().getSlug() == 'tagCategory'`,
					'@display': "['name','tags']",
					'@expands': `['entity.tags']`,
					'@order': `entity.sequence|ASC`
				}).then((res) => {
					console.log('标签二级分类', res.data)
					if (res.data && res.data.length > 0) {
						for(let i of res.data){
							i.tags.sort((a,b) => {
								return a.listOrder - b.listOrder
							})
						}
						this.tagCategories = res.data
						uni.hideLoading()
					} else {
						// 如果无标签分类的，就直接查产品，显示产品
						let filter = `entity.getCategory().getParent().getId() == ${this.choosedCategory} && entity.getIsOnSale() == true`
						this.request.get(`api/products`, {
							'@filter': filter,
							'@display': "['id','specifications','cover','name','category']"
						}).then((res) => {
							console.log('产品', res.data)
							this.products = res.data
							uni.hideLoading()
						})
					}
				})
			},
			// 搜索
			searchProduct() {
				if (this.keyword.trim() == '') {
					uni.showToast({
						title: '请输入搜索内容',
						icon: 'none'
					})
					return
				}
				uni.navigateTo({
					url: `/pages/product/search?keyword=${this.keyword}`
				})
			},
			changeCategory(id) {
				if (this.isLoading) return
				if (this.choosedCategory != id || id == 0) {
					this.choosedCategory = id;
					this.getTags()
				}
				this.categoryId = 0
				// for(let category of this.categories){
				// 	if(category.id == id){
				// 		let itemList = []
				// 		for (let i of category.children) {
				// 			if (i.type.id == 1) {
				// 				itemList.push(i)
				// 			}
				// 		}
				// 		this.itemList = itemList
				// 	}
				// }
			},
			setCategory(id) {
				console.log(id)
				this.categoryId = id
				// 如果有产品的，重新搜索产品
				if(this.products && this.products.length > 0){
					uni.showLoading()
					// 如果无标签分类的，就直接查产品，显示产品
					let filter = `entity.getCategory().getParent().getId() == ${this.choosedCategory} && entity.getIsOnSale() == true && entity.getCategory().getId() ==${this.categoryId}`
					this.request.get(`api/products`, {
						'@filter': filter,
						'@display': "['id','specifications','cover','name','category']"
					}).then((res) => {
						console.log('产品', res.data)
						this.products = res.data
						uni.hideLoading()
					})
				}
			},
			wxlogin() {
				let _this = this;
				uni.login({
					provider: "weixin",
					success: function(res) {
						let data = {
							code: res.code
						}
						_this.request.get("wechat/mini/login", data).then((res) => {
							if (res.data.token) {
								uni.setStorageSync('api_token', res.data.token);
								_this.getCategories()
							} else {
								uni.showModal({
									title: '提示',
									content: '获取注册信息失败，请重试',
									showCancel: false,
									success: () => {}
								})
								uni.hideLoading()
							}
						}).catch((err) => {
							uni.showModal({
								title: '提示',
								content: '获取注册信息失败，请重试',
								showCancel: false,
								success: () => {}
							})
							uni.hideLoading()
						})
					},
				});
			}
		}
	}
</script>

<style scoped>
	.tag {
		padding: 10px 0px;
		margin: 5px;
	}

	.tag-title {
		padding: 10px;
	}

	.content {
		position: relative;
	}

	.category {
		padding: 10px;
		text-align: center;
	}

	.left {
		background-color: #f3f3f3;
		height: calc(100vh - 50px);
		width: 25%;
		float: left;
	}

	.right {
		max-height: calc(100vh - 50px);
		/* display: flex; */
		overflow: auto;
		width: 75%;
		/* float: left; */
	}

	.active {
		background-color: white;
		border-radius: 20px 0px 0px 20px;
		color: #bc927a;
		display: flex;
		align-items: center;
		/* 垂直居中 */
		justify-content: center;
		padding: 3px 0px;
	}

	.activity-item {
		display: flex;
		padding: 30rpx;
		border-bottom: 1rpx solid #eee;
	}

	.product-img {
		width: 150rpx;
		height: 150rpx;
		border-radius: 10rpx;
	}

	.product-info {
		flex: 1;
		margin-left: 20rpx;
	}

	.product-name {
		font-size: 32rpx;
		color: #333;
		font-size: 14px;
	}

	.product-price {
		font-size: 28rpx;
		color: #e4393c;
		margin-top: 10rpx;
	}

	.category-name {
		background-color: #bc927a;
		font-size: 12px;
		color: #fff;
		padding: 0px 5px;
		border-radius: 5px;
		margin-top: 5px;
	}


	.t-container {
		padding: 20rpx;
		margin-bottom: 10px;
	}

	.t-title {
		font-size: 36rpx;
		font-weight: bold;
		text-align: center;
		padding: 30rpx 0;
		color: #333;
		border-bottom: 1rpx solid #eee;
		margin-bottom: 30rpx;
	}

	.image-grid {
		display: flex;
		/* 启用flex布局 */
		flex-wrap: wrap;
		/* 允许换行 */
		margin: -5px;
		/* 负边距抵消图片间距 */
	}

	.image-div {
		width: calc(33.333% - 10px);
		/* 每行3个，减去间距 */
		margin: 5px;
		/* 图片间距 */
		object-fit: cover;
		/* 保持比例填充容器 */
		border-radius: 10px;
	}

	.container {
		padding-bottom: 20rpx;
		background: #f3f3f3;
	}

	/* 横向滚动容器 */
	.scroll-view {
		width: 100%;
		white-space: nowrap;
		/* 关键：禁止换行 */
	}

	/* 按钮基础样式 */
	.button-item {
		display: inline-block;
		height: 50rpx;
		line-height: 50rpx;
		padding: 0 30rpx;
		margin: 0 15rpx;
		border-radius: 14rpx;
		background-color: #fff;
		color: #bc927a;
		font-size: 24rpx;
		text-align: center;
		box-sizing: border-box;
		transition: all 0.3s;
	}

	.left-button {
		display: inline-block;
	}

	/* 选中状态样式 */
	.button-item.active {
		background-color: #bc927a;
		color: white;
		font-weight: bold;
	}

	/* 第一个和最后一个按钮的边距调整 */
	.button-item:first-child {
		margin-left: 30rpx;
	}

	.button-item:last-child {
		margin-right: 30rpx;
	}
</style>